package com.cg.filter;

import com.cg.entity.Source;
import com.cg.service.UserTokenService;
import com.cg.vo.LoginUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * @ClassName SourceFilter
 * @Description TODO
 * @Author CG
 * @Date 2024/1/14 21:16
 **/
public class SourceFilter implements GlobalFilter, Ordered {

    private final Logger logger = LoggerFactory.getLogger(SourceFilter.class);
    @Resource
    private UserTokenService userTokenService;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getHeaders().getFirst("token");
        String requestPath = request.getPath().toString();
        if (requestPath.equals("/user/getUserByToken")) {
            //通过token获取用户信息请求
            return chain.filter(exchange);
        }
        if (token == null || token.equals("")) {
            return chain.filter(exchange);
        }
        //token存在
        //根据token获取用户信息 及权限信息
        LoginUserVo loginUserVo = userTokenService.getUserByToken(token);
        if (loginUserVo == null) {
            //没有权限信息
            logger.info("没有权限信息");
            exchange.getResponse().setStatusCode(HttpStatus.REQUEST_TIMEOUT);
            return exchange.getResponse().setComplete();
        }
        //获取所有权限
        List<Source> sourceList = loginUserVo.getSourceList();
        if (sourceList != null && sourceList.size() > 0) {
            for (Source source : sourceList) {
                String sourceUrl = source.getSourceUrl();
                System.out.println("requestPath" + requestPath);
                System.out.println("url" + sourceUrl);
                if (sourceUrl != null && !sourceUrl.equals("")) {
                    if (sourceUrl.indexOf(requestPath) >= 0) {
                        logger.info("用户拥有该请求的权限");
                        return chain.filter(exchange);
                    }
                }
            }
        }
        logger.info("没有所匹配的权限");
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        return exchange.getResponse().setComplete();

    }

    @Override
    public int getOrder() {
        return 2;
    }
}
